package com.learn.multi_thread.D_CompletableFuture.demo;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class GoodsController {
    private GoodService goodService = new GoodService();
    private RepoService repoService = new RepoService();
    private CommentService commentService = new CommentService();

    public List<Goods> getGoods() throws ExecutionException, InterruptedException {
        CompletableFuture<List<Goods>> goodsFuture = CompletableFuture.supplyAsync(() -> goodService.getGoods());
        CompletableFuture cf = goodsFuture.thenApplyAsync(goods -> {
            goods.stream().map(goods1 -> CompletableFuture.supplyAsync(() -> {
                goods1.setRepo(repoService.getRepoByGoodsId(goods1.getId()));
                return goods1;
            }).thenCompose(goods2 -> CompletableFuture.supplyAsync(() -> {
                goods2.setComment(commentService.getComment(goods2.getId()));
                return goods2;
            }))).toArray(size -> new CompletableFuture[size]);
            return goods;
        });
        return (List<Goods>) cf.handleAsync((goods, th) -> th != null ? "系统繁忙" : goods).get();
    }
}
